﻿using System;
using System. Collections. Generic;
using System. Linq;
using System. Net;
using System. Windows;
using System. Windows. Controls;
using System. Xml. Linq;
using Microsoft. Phone. Controls;
using NextApp. WP7. AppConfig;
using NextApp. WP7. Models;
using NextApp. WP7. Cache. NextApp;

namespace NextApp. WP7. View. Controls
{
    public partial class CatalogList : UserControl
    {
        #region Initialize
        public CatalogList( )
        {
            InitializeComponent( );
        }

        /// <summary>
        /// 表示本控件是否属于 MainPage 的子控件
        /// </summary>
        public bool IsHostByMainPage { get; set; }
         
        /// <summary>
        /// 重新加载数据   该方法需要被 MainPage 根据 Pivot 根据 SelectedIndex 的更改而重新运行
        /// </summary>
        public void Reload( )
        {
            if ( NextAppSingleton.Instance.IsReady == false )
            {
                MessageBox. Show("网络还未加载完毕");
                return;
            }
			WebClient client = Util. Tool. GetWebClient;
            client. DownloadStringCompleted += (s, e1) =>
            {
				CacheNextApp. Instance. MinusBandwidthCost(new BandwidthCostNextApp { cost = BandwidthCostNextApp. Catalog_List });
                if ( e1. Error != null )
                {
                    MessageBox. Show("添加文章分类失败", "网络错误", MessageBoxButton. OK);
                    return;
                }
				XElement nextApp;
				try
				{
					nextApp = XElement. Parse(e1. Result);
				}
				catch ( Exception )
				{
					return;
				}
                Catalog[ ] catalogs = nextApp.Elements("catalogs") == null ?
                    null :
                    nextApp. Elements("catalogs"). Elements("catalog"). Select(
                    c =>
                    {
                        Dictionary<string, string> attributes = c. Attributes( ). ToDictionary(a => a. Name. LocalName, a => a. Value);
                        return new Catalog
                        {
                            description = attributes[ "description" ],
                            id = attributes[ "id" ]. ToInt32( ),
                            name = attributes[ "name" ],
                        };
                    }). ToArray( );
                //显示出来
                this. list_Catalogs. ItemsSource = catalogs;
                //保存起来
                DataSingleton. Instance. catalogs = catalogs;
                //隐藏进度条
                this. IsDisplayProgressBar(false);
            };
            if ( NextAppSingleton.Instance.url_catalog_list.IsNotNullOrWhitespace() )
            {
                client. DownloadStringAsync(new Uri(Config. Instance. GetApi(string. Format("{0}&guid={1}", NextAppSingleton. Instance. url_catalog_list, Guid. NewGuid( ))), UriKind. Absolute));
				CacheNextApp. Instance. AddBandwidthCost(new BandwidthCostNextApp { cost = BandwidthCostNextApp. Catalog_List });
                //显示进度条
                this. IsDisplayProgressBar(true);
            }
        }

        /// <summary>
        /// 是否显示进度条
        /// </summary>
        /// <param name="visible">是否显示</param>
        private void IsDisplayProgressBar(bool visible)
        {
            if ( this. IsHostByMainPage )
            {
                EventSingleton. Instance. RaiseOnMainPageLoading(visible);
            }
        }

        #endregion

        #region 进入不同的分类查看文章
        private void list_Catalogs_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Catalog c = this. list_Catalogs. SelectedItem as Catalog;
            this. list_Catalogs. SelectedItem = null;
            if ( c != null )
            {
                ( Application. Current. RootVisual as PhoneApplicationFrame ). Navigate(new Uri(string. Format("/View/Posts.xaml?catalog={0}&title={1}", c. id, c. name), UriKind. Relative));
            }
        }
        #endregion

        #region 将文章分类订到桌面上
        private void menuItem_PostPinToStart_Click(object sender, RoutedEventArgs e)
        {
            Catalog c = ( sender as MenuItem ). DataContext as Catalog;
            if ( c != null )
            {
                Util. Tool. CreateShellTile(c);
            }
        }
        #endregion
    }
}
